<template>
	<view class="address-edit-container page-container">
		<!-- 地址表单 -->
		<view class="form-section">
			<view class="form-item">
				<text class="form-label">收货人</text>
				<input class="form-input" placeholder="请输入收货人姓名" v-model="formData.realname" maxlength="20" />
			</view>

			<view class="form-item">
				<text class="form-label">手机号</text>
				<input class="form-input" placeholder="请输入手机号码" v-model="formData.mobile" type="number"
					maxlength="11" />
			</view>

			<view class="form-item" @click="selectRegion">
				<text class="form-label">所在地区</text>
				<view class="form-select">
					<text class="select-text" :class="{ placeholder: !regionText }">
						{{ regionText || '请选择省市区' }}
					</text>
					<u-icon name="arrow-right" size="16" color="#999"></u-icon>
				</view>
			</view>

			<view class="form-item">
				<text class="form-label">详细地址</text>
				<textarea class="form-textarea" placeholder="请输入详细地址（街道、门牌号等）" v-model="formData.address"
					maxlength="200"></textarea>
			</view>

			<view class="form-item">
				<text class="form-label">地址标签</text>
				<view class="tag-list">
					<view class="tag-item" v-for="(tag, index) in tagOptions" :key="index"
						:class="{ active: formData.tag_name === tag.value }" @click="selectTag(tag.value)">
						<text class="tag-text">{{ tag.label }}</text>
					</view>
				</view>
			</view>

			<view class="form-item switch-item">
				<text class="form-label">设为默认地址</text>
				<switch :checked="formData.is_default===1" @change="toggleDefault" color="#1c705e"></switch>
			</view>
		</view>

		<!-- 位置选择 -->
		<view class="location-section" @click="chooseLocation">
			<view class="location-header">
				<view class="location-left">
					<u-icon name="map" size="20" color="#1c705e"></u-icon>
					<text class="location-text">选择位置</text>
				</view>
				<u-icon name="arrow-right" size="16" color="#999"></u-icon>
			</view>
			<text class="location-tip">点击可在地图上选择精确位置</text>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-actions">
			<button class="delete-btn" v-if="isEdit" @click="deleteAddress">删除地址</button>
			<button class="save-btn" @click="saveAddress">保存地址</button>
		</view>

		<!-- 地区选择器 -->
		<u-picker ref="uPicker" :columns="columns" :show="regionPickerShow" mode="region" :defaultIndex="regionValue"
			@confirm="confirmRegion" @cancel="regionPickerShow = false" @change="onColumnChange"></u-picker>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isEdit: false,
				addressId: '',
				regionPickerShow: false,
				regionValue: [0, 0, 0], // 默认选中第一个省市区
				regionData: [], // 省市区原始数据
				columns: [
					[],
					[],
					[]
				], // 三级联动的列数据
				columnData: [
					['深圳', '厦门', '上海', '拉萨'],
					['得州', '华盛顿', '纽约', '阿拉斯加']
				],
				formData: {
					realname: '',
					mobile: '',
					province: {},
					city: {},
					town: {},
					street: {},
					address: '',
					is_default: 0,
					tag_name: 'home',
					latitude: 0,
					longitude: 0
				},
				tagOptions: [{
						label: '家',
						value: 'home'
					},
					{
						label: '公司',
						value: 'company'
					},
					{
						label: '学校',
						value: 'school'
					},
					{
						label: '其他',
						value: 'other'
					}
				]
			}
		},
		computed: {
			// 地区文本
			regionText() {
				if (this.formData.province.name && this.formData.city.name && this.formData.town.name) {
					return `${this.formData.province.name} ${this.formData.city.name} ${this.formData.town.name}`
				}
				return ''
			}
		},
		onLoad(options) {
			// 加载省市区数据
			this.loadRegionData()

			if (options.id) {
				this.isEdit = true
				this.addressId = options.id
				this.loadAddressDetail()
			}
		},
		methods: {
			// 加载省市区数据
			loadRegionData() {
				// 导入完整的省市区数据
				uni.request({
					url: this.$tools.baseUrl() + '/static/json/pcs-code.json', // JSON文件的URL
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200) {
							this.regionData = res.data
							this.initColumns()
						} else {
							uni.showToast({
								title: '地区数据加载失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('加载省市区数据失败:', err)
						uni.showToast({
							title: '地区数据加载失败',
							icon: 'none'
						})
					}
				});
			},

			// 初始化列数据
			initColumns() {
				if (this.regionData.length === 0) return

				// 初始化省份列表
				this.columns[0] = this.regionData.map(province => province.name)

				// 初始化第一个省份的城市列表
				if (this.regionData[0] && this.regionData[0].children) {
					this.columns[1] = this.regionData[0].children.map(city => city.name)

					// 初始化第一个城市的区县列表
					if (this.regionData[0].children[0] && this.regionData[0].children[0].children) {
						this.columns[2] = this.regionData[0].children[0].children.map(area => area.name)
					}
				}

				// console.log('省市区列数据初始化完成:', this.columns)
			},

			// 加载地址详情
			loadAddressDetail() {
				this.$api.user.GetAddressInfo({
					id: this.addressId
				}).then(res => {
					this.formData = res.data
					this.formData.mobile = this.$secret.decryptAES(this.formData.mobile)
					this.formData.address = this.$secret.decryptAES(this.formData.address)
					this.formData.province = this.$tools.parseJsonObject(this.formData.province)
					this.formData.city = this.$tools.parseJsonObject(this.formData.city)
					this.formData.town = this.$tools.parseJsonObject(this.formData.town)
					this.formData.street = this.$tools.parseJsonObject(this.formData.street)
					// 设置地区选择器的值（用于编辑时回显）
					this.setRegionValue()
				})
			},

			// 设置地区选择器的值（用于编辑时回显）
			setRegionValue() {
				if (!this.formData.province.name || !this.formData.city.name || !this.formData.town.name) {
					return
				}

				// 查找省份索引
				const provinceIndex = this.regionData.findIndex(p => p.name === this.formData.province.name)
				if (provinceIndex === -1) return

				// 查找城市索引
				const province = this.regionData[provinceIndex]
				const cityIndex = province.children.findIndex(c => c.name === this.formData.city.name)
				if (cityIndex === -1) return

				// 查找区县索引
				const city = province.children[cityIndex]
				const areaIndex = city.children.findIndex(a => a.name === this.formData.town.name)
				if (areaIndex === -1) return

				// 更新列数据
				this.columns[1] = province.children.map(city => city.name)
				this.columns[2] = city.children.map(area => area.name)

				// 设置选中值
				this.regionValue = [provinceIndex, cityIndex, areaIndex]
			},

			// 选择地区
			selectRegion() {
				this.regionPickerShow = true
			},

			// 确认地区选择
			confirmRegion(e) {
				// console.log('地区选择结果:', e)
				// console.log('当前regionValue:', this.regionValue)
				const value = e.indexs
				if (value && value.length > 0) {
					// 获取选中的省市区数据
					const province = this.regionData[value[0]]
					const city = province ? province.children[value[1]] : null
					const area = city ? city.children[value[2]] : null

					console.log('选中的地区:', province?.name, city?.name, area?.name)

					if (province && city && area) {
						this.formData.province = {
							code: province.code,
							name: province.name
						}
						this.formData.city = {
							code: city.code,
							name: city.name
						}
						this.formData.town = {
							code: area.code,
							name: area.name
						}
						this.regionValue = [value[0], value[1], value[2]]

						uni.showToast({
							title: '地区选择成功',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: '地区数据异常',
							icon: 'none'
						})
					}
				}

				this.regionPickerShow = false
			},

			// 处理列变化（三级联动）
			onColumnChange(e) {
				const column = e.columnIndex
				const value = e.index
				// console.log('列变化:', column, value)

				// 更新当前的regionValue
				this.regionValue[column] = value

				if (column === 0) {
					// 省份变化，更新城市和区县
					this.columns = [
						this.columns[0],
						[],
						[]
					];
					const province = this.regionData[value]
					if (province && province.children) {
						this.columns[1] = province.children.map(city => city.name)

						// 重置城市和区县的选择
						this.regionValue[1] = 0
						this.regionValue[2] = 0

						// 更新区县（选择第一个城市的区县）						
						if (province.children[0] && province.children[0].children) {
							this.columns[2] = province.children[0].children.map(area => area.name)
						} else {
							this.columns[2] = []
						}
					}
				} else if (column === 1) {
					// 城市变化，更新区县
					this.columns = [
						this.columns[0],
						this.columns[1],
						[]
					];
					const provinceIndex = this.regionValue[0]
					const province = this.regionData[provinceIndex]
					if (province && province.children && province.children[value]) {
						const city = province.children[value]

						// 重置区县的选择
						this.regionValue[2] = 0

						if (city.children) {
							this.columns[2] = city.children.map(area => area.name)
						} else {
							this.columns[2] = []
						}
					}
				}

				// console.log('更新后的regionValue:', this.regionValue)
			},

			// 选择标签
			selectTag(tag) {
				this.formData.tag_name = tag
			},

			// 切换默认地址
			toggleDefault(e) {
				this.formData.is_default = e.detail.value ? 1 : 0;
			},

			// 选择位置
			chooseLocation() {
				uni.chooseLocation({
					success: (res) => {
						this.formData.latitude = res.latitude;
						this.formData.longitude = res.longitude;
						this.formData.address = res.address + res.name;
						// 可以根据选择的位置自动填充地址信息
						if (res.address) {
							// 解析地址信息
							this.parseAddress(res.address)
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '获取位置失败',
							icon: 'none'
						})
					}
				})
			},

			// 解析地址
			parseAddress(address) {
				// 这里可以实现地址解析逻辑
				if (address && address !== '') {
					// 正则匹配（适用于大多数中文地址）
					const match = address.match(/(.+省|.+自治区|.+市)?(.+市)?(.+区|.+县|.+旗)?/);
					if (match) {
						const province_name = match[1] || ''; // 广东省
						const city_name = match[2] || '直辖市'; // 深圳市
						const town_name = match[3] || ''; // 南山区

						// 查找省份索引
						const provinceIndex = this.regionData.findIndex(p => p.name === province_name)
						// 查找城市索引
						const province = this.regionData[provinceIndex]
						const cityIndex = province.children.findIndex(c => c.name === city_name)
						// 查找区县索引
						const city = province.children[cityIndex]
						const areaIndex = city.children.findIndex(a => a.name === town_name)

						this.formData.province = {
							code: provinceIndex >= 0 ? this.regionData[provinceIndex].code : '',
							name: province_name
						};
						this.formData.city = {
							code: cityIndex >= 0 ? province.children[cityIndex].code : '',
							name: city_name
						};
						this.formData.town = {
							code: areaIndex >= 0 ? city.children[areaIndex].code : '',
							name: town_name
						};
						if (provinceIndex >= 0 && cityIndex >= 0 && areaIndex >= 0) {
							this.regionValue = [provinceIndex, cityIndex, areaIndex]
						}
						this.formData.address = this.formData.address.replace(province_name + city_name + town_name, '')
						this.formData.address = this.formData.address.replace(province_name + town_name, '')
					}
				}
			},

			// 保存地址
			saveAddress() {
				// 表单验证
				if (!this.formData.realname.trim()) {
					uni.showToast({
						title: '请输入收货人姓名',
						icon: 'none'
					})
					return
				}

				if (!this.formData.mobile.trim()) {
					uni.showToast({
						title: '请输入手机号码',
						icon: 'none'
					})
					return
				}

				// 手机号格式验证
				const phoneReg = /^1[3-9]\d{9}$/
				if (!phoneReg.test(this.formData.mobile)) {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none'
					})
					return
				}

				if (!this.formData.province.name.trim() || !this.formData.city.name.trim() || !this.formData.town.name
					.trim()) {
					uni.showToast({
						title: '请选择所在地区',
						icon: 'none'
					})
					return
				}

				if (!this.formData.address.trim()) {
					uni.showToast({
						title: '请输入详细地址',
						icon: 'none'
					})
					return
				}

				// 保存地址
				uni.showLoading({
					title: this.isEdit ? '保存中...' : '添加中...'
				})

				// 保存地址信息
				this.$api.user.SaveAddress(this.formData).then(res => {
					uni.hideLoading()
					uni.showToast({
						title: res.msg,
						icon: 'success'
					})
					const pages = getCurrentPages()
					const prevPage = pages[pages.length - 2]
					if (prevPage) {
						prevPage.$vm.onSearch()
					}
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				})
			},

			// 删除地址
			deleteAddress() {
				uni.showModal({
					title: '删除地址',
					content: '确定要删除这个收货地址吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '删除中...'
							})

							this.$api.user.DelAddress({
								id: this.formData.id
							}).then(res => {
								uni.hideLoading()
								uni.showToast({
									title: res.msg,
									icon: 'success'
								})
								const pages = getCurrentPages()
								const prevPage = pages[pages.length - 2]
								if (prevPage) {
									prevPage.$vm.onSearch()
								}
								setTimeout(() => {
									uni.navigateBack()
								}, 1500)
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.address-edit-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: calc(180rpx + env(safe-area-inset-bottom));
	}

	.form-section {
		background-color: #ffffff;
		margin: 20rpx;
		border-radius: 12rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.form-item {
		margin-bottom: 40rpx;
	}

	.form-item:last-child {
		margin-bottom: 0;
	}

	.form-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}

	.form-input {
		width: calc(100% - 50rpx);
		padding: 24rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
		font-size: 28rpx;
	}

	.form-select {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
	}

	.select-text {
		font-size: 28rpx;
		color: #333;
	}

	.select-text.placeholder {
		color: #999;
	}

	.form-textarea {
		width: calc(100% - 50rpx);
		min-height: 120rpx;
		padding: 24rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
		font-size: 28rpx;
	}

	.tag-list {
		display: flex;
		flex-wrap: wrap;
		margin-top: 10rpx;
	}

	.tag-item {
		padding: 16rpx 32rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 40rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}

	.tag-item.active {
		border-color: #52a58a;
		background-color: #f0f8f5;
	}

	.tag-text {
		font-size: 26rpx;
		color: #666;
	}

	.tag-item.active .tag-text {
		color: #52a58a;
	}

	.switch-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.location-section {
		background-color: #ffffff;
		margin: 20rpx;
		border-radius: 12rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.location-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.location-left {
		display: flex;
		align-items: center;
	}

	.location-text {
		font-size: 28rpx;
		color: #333;
		margin-left: 12rpx;
	}

	.location-tip {
		font-size: 24rpx;
		color: #999;
		padding-left: 32rpx;
	}

	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		border-top: 1rpx solid #eee;
		padding: 20rpx 30rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		display: flex;
		gap: 16rpx;
	}

	.delete-btn {
		flex: 1;
		background-color: transparent;
		color: #666;
		border: 1rpx solid #ddd;
		border-radius: 20rpx;
		padding: 12rpx 24rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	.save-btn {
		flex: 2;
		background-color: #52a58a;
		color: #ffffff;
		border: none;
		border-radius: 20rpx;
		padding: 12rpx 24rpx;
		font-size: 24rpx;
		font-weight: 500;
	}
</style>